package com.one.odf.util;

import lombok.extern.log4j.Log4j2;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.*;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * @author zengzr
 * @desc
 * @Date 2019/5/5 14:31
 */
@Component
@Log4j2
public class BeetlUtils {
    private static CompositeResourceLoader resourceLoader;
    private static StringTemplateResourceLoader stringTemplateResourceLoader;
    private static ClasspathResourceLoader classpathResourceLoader;
    private static Configuration cfg;
    private static GroupTemplate gt;
    private static String STRING_PREFIX = "S:";
    private static String FILE_PREFIX = "F:";
    private static String path = "templates/";
    static {
        try {
            resourceLoader = new CompositeResourceLoader();
            stringTemplateResourceLoader = new StringTemplateResourceLoader();
            classpathResourceLoader = new ClasspathResourceLoader(path,"utf-8");
            resourceLoader.addResourceLoader(new StartsWithMatcher(STRING_PREFIX),stringTemplateResourceLoader);
            resourceLoader.addResourceLoader(new StartsWithMatcher(FILE_PREFIX),classpathResourceLoader);
            cfg = Configuration.defaultConfiguration();
            gt = new GroupTemplate(resourceLoader,cfg);
        } catch (IOException e) {
            log.error("beetl模版引擎初始化异常",e.getMessage(),e);
        }
    }



    public String buildString( Map<String, Object> extParam, String template) {
        Template st = gt.getTemplate(STRING_PREFIX + template);
        st.binding("result", extParam);
        return st.render();
    }

    public String buildFile(Map<String, Object> extParam, String templatePath) {
        Template st = gt.getTemplate(FILE_PREFIX + templatePath);
        st.binding("result", extParam);
        return st.render();
    }
}
